package com.codi.bus.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.http.HttpStatus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author lvgo
 * @version 1.0
 * @Description: 深沪300 加载远程数据
 * @date 18-6-29 下午5:08
 */
@Slf4j
public class SH300Util {

    /**
     * 加载远程数据
     *
     * @param url
     * @param op
     */
    public static void loadData(String url, BoundHashOperations<String, String, String> op) {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        try {
            int responseCode = httpClient.executeMethod(getMethod);
            if (responseCode == HttpStatus.OK.value()) {
                InputStream in = getMethod.getResponseBodyAsStream();

                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
                String line = null;

                while ((line = bufferReader.readLine()) != null) {
                    line = line.replace("\\n\\", "");
                    String[] array = line.split(" ");
                    if (array.length != 6) {
                        continue;
                    }
                    String tradingDay = array[0];
                    op.put(tradingDay, line); // 每次都是一次http请求
                }
            }

        } catch (HttpException e) {
            log.error("fail to http get", e);
        } catch (IOException e) {
            log.error("io exception", e);
        } finally {
            getMethod.releaseConnection();
        }
    }
}
